﻿using System;
using System.Windows.Forms;
using DiagnosisToolBL;
using System.Collections.Generic;
using com.diagnosis.tool.xml;
using System.Text.RegularExpressions;

namespace com.diagnosis.disease.builder
{
    public partial class DiseaseBuilderTool : Form
    {
        private DiseasesBuilderData mDiseasesBuilderData;

        public DiseaseBuilderTool()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            DialogResult dr = openFileDialogLoadFile.ShowDialog();
            switch (dr)
            {
                case DialogResult.OK:
                case DialogResult.Yes:
                    String fileName = openFileDialogLoadFile.FileName;
                    textBoxLoadFile.Text = fileName;
                    LoadFile(fileName);
                    btnBrowse.Enabled = false;
                    break;
            }
        }

        private void LoadFile(string pFilePath)
        {
            ClearValues(true);
            
            // Load the data
            mDiseasesBuilderData = new DiseasesBuilderData();
            mDiseasesBuilderData.LoadFromXml(pFilePath);

            // Fill the UI
            Dictionary<String, ExtendedDiseaseForBuilder>.KeyCollection names =
                mDiseasesBuilderData.GetDiseases().Keys;
            foreach(var name in names)
            {
                listBoxDiseasesNames.Items.Add(name);
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {
            ClearValues(false);
            
            // Get selected disease
            if (null == listBoxDiseasesNames.SelectedItem)
            {
                MessageBox.Show("Please select a disease");
                return;
            }

            // Extract the selecte disease name
            string selectedDiseaseName = listBoxDiseasesNames.SelectedItem.ToString();

            // Extract the disease from the map
            var disease = 
                mDiseasesBuilderData.GetDiseases()[selectedDiseaseName];

            FillGui(disease);
        }

        private void FillGui(ExtendedDiseaseForBuilder pDiseaseForBuilder)
        {
            textBoxDiseaseName.Text = pDiseaseForBuilder.GetDisease().DiseaseName;
            textBoxWIKILink.Text = pDiseaseForBuilder.GetDisease().LinkToWiki;
            
            // Fill ICD 9
            FillIcd9(pDiseaseForBuilder.GetDisease().ICD9List);

            // Fill Symptoms
            FillSymptoms(pDiseaseForBuilder.GetSymptoms());
        }

        private void FillSymptoms(List<SympNameIDPair> pSymptoms)
        {
            var allNames = "";

            foreach (var curSymp in pSymptoms)
            {
                allNames += curSymp.Name + "\r\n";
                listViewSymptoms.Items.Add(curSymp.Name + " [" + curSymp.ID + "]");
            }
            textBoxSymptoms.Text = allNames.Substring(0, allNames.Length - "\r\n".Length);
        }

        private void FillIcd9(tool.xml.ICD9[] pIcd9List)
        {
            if (null != pIcd9List)
            {
                for (var i = 0; i < pIcd9List.Length; i++)
                {
                    var num = pIcd9List[i].Number;
                    var val = pIcd9List[i].Value;

                    switch (i)
                    {
                        case 0:
                            textBoxIDC91Num.Text = num;
                            textBoxIDC91Val.Text = val;
                            break;
                        case 1:
                            textBoxIDC92Num.Text = num.ToString();
                            textBoxIDC92Val.Text = val;
                            break;
                        case 2:
                            textBoxIDC93Num.Text = num.ToString();
                            textBoxIDC93Val.Text = val;
                            break;
                    }
                }
            }
        }

        private void btnExtractSymptoms_Click(object sender, EventArgs e)
        {
            RefreshSymptoms();
        }

        private void RefreshSymptoms()
        {
            // Clear
            listViewSymptoms.Items.Clear();

            // Keep new values - we will need that to assign new ids
            var values = new List<String>();

            // Take the string and convert it to the list view
            string[] symptomsArr = Regex.Split(textBoxSymptoms.Text, "\r\n");
            foreach (var curSymp in symptomsArr)
            {
                if (!values.Contains(curSymp))
                {
                    values.Add(curSymp);
                }
            }

            var updatedDisease = GuiToDisease();

            var extendedDisease =
                mDiseasesBuilderData.AddUpdateDisease(updatedDisease, values);

            FillSymptoms(extendedDisease.GetSymptoms());
        }

        private Disease GuiToDisease()
        {
            var disease = new Disease();
            disease.DiseaseName = textBoxDiseaseName.Text;
            disease.LinkToWiki = textBoxWIKILink.Text;
            
            // ICD9
            Icd9GuiToDisease(disease);

            return disease;
        }

        private void Icd9GuiToDisease(Disease pDisease)
        {
            var list = new List<ICD9>();

            AddIcd9(textBoxIDC91Num, textBoxIDC91Val, list);
            AddIcd9(textBoxIDC92Num, textBoxIDC92Val, list);
            AddIcd9(textBoxIDC93Num, textBoxIDC93Val, list);

            pDisease.ICD9List = list.ToArray();
        }

        private static void AddIcd9(TextBox pTextBoxIcd9Num, TextBox pTextBoxIcd9Val, List<ICD9> pList)
        {
            if (!String.IsNullOrEmpty(pTextBoxIcd9Num.Text) &&
                 !String.IsNullOrEmpty(pTextBoxIcd9Val.Text))
            {
                var icd9 = new ICD9();
                icd9.Number = pTextBoxIcd9Num.Text;
                icd9.Value = pTextBoxIcd9Val.Text;
                pList.Add(icd9);
            }
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            if (null == listViewSymptoms.SelectedItems || listViewSymptoms.SelectedItems.Count != 2)
            {
                MessageBox.Show("Please select two symptoms to merge");

                return;
            }

            var symp1 = GetSympName(listViewSymptoms.SelectedItems[0].Text);
            var symp2 = GetSympName(listViewSymptoms.SelectedItems[1].Text);

            mDiseasesBuilderData.MergeSymptoms(symp1, symp2);

            RefreshSymptoms();
        }

        private static String GetSympName(String pSympWithId)
        {
            return pSympWithId.Substring(0, pSympWithId.IndexOf('[')).Trim();
        }


        private void ClearValues(Boolean pLoadFile)
        {
            if (pLoadFile)
            {
                listBoxDiseasesNames.Items.Clear();
            }

            textBoxDiseaseName.Text = "";
            textBoxWIKILink.Text = "";
            textBoxIDC91Num.Text = "";
            textBoxIDC91Val.Text = "";
            textBoxIDC92Num.Text = "";
            textBoxIDC92Val.Text = "";
            textBoxIDC93Num.Text = "";
            textBoxIDC93Val.Text = "";
            textBoxSymptoms.Text = "";
            listViewSymptoms.Items.Clear();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(textBoxLoadFile.Text))
            {
                mDiseasesBuilderData.SaveToXml(textBoxLoadFile.Text);
            }
        }

        private void btnSaveCurDisease_Click(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(textBoxDiseaseName.Text))
            {
                MessageBox.Show("Pleaes type some information for the disease");
            }

            RefreshSymptoms();
            
            // Save the current working
            mDiseasesBuilderData.SaveDisease();
            
            var found = false;
            foreach (var curDName in listBoxDiseasesNames.Items)
            {
                if (textBoxDiseaseName.Text.Equals(curDName.ToString()))
                {
                    found = true;
                    break;
                }
            }
            if (!found)
            {
                listBoxDiseasesNames.Items.Add(textBoxDiseaseName.Text);
            }

            ClearValues(false);
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            // Get selected disease
            if (null == listBoxDiseasesNames.SelectedItem)
            {
                MessageBox.Show("Please select a disease");
                return;
            }

            String diseaseNameToDelete = listBoxDiseasesNames.SelectedItem.ToString();
            mDiseasesBuilderData.DeleteDisease(diseaseNameToDelete);

            listBoxDiseasesNames.Items.Remove(listBoxDiseasesNames.SelectedItem);
        }
    }
}
